package com.liwei.lwmail.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.liwei.common.constant.CartConstant;
import com.liwei.common.utils.R;
import com.liwei.lwmail.cart.feign.ProductFeignService;
import com.liwei.lwmail.cart.interceptor.CartInterceptor;
import com.liwei.lwmail.cart.service.CartService;
import com.liwei.lwmail.cart.vo.Cart;
import com.liwei.lwmail.cart.vo.CartItem;
import com.liwei.lwmail.cart.vo.SkuInfoVo;
import com.liwei.lwmail.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public CartItem add(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOPs = getCartOPs();
        String o = (String) cartOPs.get(skuId.toString());

        if (StringUtils.isEmpty(o)){
            CartItem item = new CartItem();
            //购物车没有此商品
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                //1、远程查询skuId的信息
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    //将商品添加到购物车
                    item.setSkuId(skuId);
                    item.setDefaultImage(skuInfo.getSkuDefaultImg());
                    item.setPrice(skuInfo.getPrice());
                    item.setCount(num);
                    item.setTitle(skuInfo.getSkuTitle());
                }
            }, executor);

            CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
                //远程查询sku的组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                item.setSaleAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(future,future2).get();

            cartOPs.put(skuId.toString(),JSON.toJSONString(item));
            return item;
        }else {
            //已经有过该商品,增加该商品数量
            CartItem cartItem = JSON.parseObject(o, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            //更新redis
            cartOPs.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItemBySkuId(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOPs = getCartOPs();
        String o = (String) cartOPs.get(skuId.toString());
        return JSON.parseObject(o,CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        BoundHashOperations<String, Object, Object> cartOPs = getCartOPs();
        //1、区分登陆状态
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserId();
        String tempCartKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
        if (userInfoTo.getUserId() != null){
            //登录状态
            //如果临时购物车没有合并，则进行合并
            BoundHashOperations<String, Object, Object> tempCartOps = redisTemplate.boundHashOps(tempCartKey);
            List<CartItem> tempCartItems = getCartItems(tempCartKey, tempCartOps);
            if (tempCartItems != null){
                //需要合并
                for (CartItem tempCartItem : tempCartItems) {
                    add(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清空离线购物车
                clearCart(tempCartKey);
            }
            //获取登录后的购物车(包含合并过来的离线购物车)
            List<CartItem> cartItems = getCartItems(cartKey, cartOPs);
            cart.setItems(cartItems);
        }else {
            //没登录
            //获取离线购物车
            List<CartItem> cartItems = getCartItems(tempCartKey, cartOPs);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 获取到要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOPs() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        //1、判断是否登录
        if (userInfoTo.getUserId() != null){
            //登录
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserId();
        }else {
            //未登录
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        return hashOps;
    }

    /**
     * 获取购物车的所有购物项
     * @param cartKey
     * @param cartOPs
     * @return
     */
    private List<CartItem> getCartItems(String cartKey, BoundHashOperations<String, Object, Object> cartOPs){
        List<Object> values = cartOPs.values();
        if (values != null && values.size() > 0){
            List<CartItem> collect = values.stream().map(item -> {
                CartItem cartItem = JSON.parseObject((String)item, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 清空购物车
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void updateItemChecked(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOPs = getCartOPs();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCheck(check == 1);

        cartOPs.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void updateItemNum(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOPs = getCartOPs();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCount(num);

        cartOPs.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOPs = getCartOPs();
        cartOPs.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        List<CartItem> cartItems = getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserId(), getCartOPs());
        if (cartItems != null){
            List<CartItem> collect = cartItems.stream()
                    .filter(CartItem::getCheck)
                    .map(item->{
                        //更新为最新的价格
                        BigDecimal skuPrice = productFeignService.getSkuPrice(item.getSkuId());
                        item.setPrice(skuPrice);
                        return item;
                    })
                    .collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
